package andy.ham;

import android.content.Context;
import android.database.Cursor;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Administrator on 2018/6/19.
 */

public class MyAdapter extends SimpleCursorAdapter{
    private ArrayList<Long> selection = new ArrayList<Long>();//记录被选中条目id
    private int mCheckBoxId = 0;//listView条目的样式对应的xml资源文件名（必须包含checkbox）
    private String mIdColumn;//数据库表的id名称
    public MyAdapter(Context context, int layout, Cursor c,
                     String[] from, int[] to, int checkBoxId, String idColumn,
                     int flags)
    {
        super(context, layout, c, from, to, flags);
        mCheckBoxId = checkBoxId;
        mIdColumn = idColumn;
    }
    @Override
    public int getCount()
    {
        return super.getCount();
    }
    @Override
    public Object getItem(int position)
    {
        return super.getItem(position);
    }
    @Override
    public long getItemId(int position)
    {
        return super.getItemId(position);
    }
    @Override
    public View getView(final int position, View convertView,
                        ViewGroup parent)
    {
        View view = super.getView(position, convertView, parent);
        final CheckBox checkBox= (CheckBox) view.findViewById(mCheckBoxId);
        /*if(LifeDiary.isMulselected){
            System.out.println(position);
            checkBox.setVisibility(View.VISIBLE);

            LifeDiary.isMulselected = false;
        }*/
        checkBox.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Cursor cursor = getCursor();
                cursor.moveToPosition(position);
                if(checkBox.isChecked())//如果被选中则将id保存到集合中
                {
                    selection.add(cursor.getLong(cursor.getColumnIndex(mIdColumn)));
                }
                else//否则移除
                {
                    selection.remove(new Long(cursor.getLong(cursor.getColumnIndex(mIdColumn))));
                    //Toast.makeText(this, "has removed " + cursor.getInt(cursor.getColumnIndex(mIdColumn)), 0).show();
                }
            }
        });
        //把添加监听器的方法加到初始化view中checkBox状态的代码之前
        checkBox.setChecked(checkBox.isChecked());
        return view;
    }
    public ArrayList<Long> getSelectedItems()
    {
        return selection;
    }


}
